<template>
  <div class="jnpf-univer-design-content" v-loading="loading">
    <div class="univer-design-container" :id="containerEleId" />
  </div>
</template>

<script lang="ts" setup>
  import '@univerjs/design/lib/index.css';
  import '@univerjs/ui/lib/index.css';
  import '@univerjs/docs-ui/lib/index.css';
  import '@univerjs/sheets-ui/lib/index.css';
  import '@univerjs/sheets-formula-ui/lib/index.css';
  import '@univerjs/sheets-numfmt/lib/index.css';
  import '@univerjs/sheets-hyper-link-ui/lib/index.css';
  import '@univerjs/drawing-ui/lib/index.css';
  import '@univerjs/sheets-drawing-ui/lib/index.css';
  import '@univerjs/find-replace/lib/index.css';
  import '@univerjs/sheets-filter-ui/lib/index.css';
  import '@univerjs/sheets-sort-ui/lib/index.css';
  import '@univerjs/sheets-data-validation-ui/lib/index.css';
  import '@univerjs/sheets-conditional-formatting-ui/lib/index.css';
  import '@univerjs/sheets-crosshair-highlight/lib/index.css';
  import '@univerjs-pro/sheets-pivot-ui/lib/index.css';
  import '@univerjs/thread-comment-ui/lib/index.css';
  import '@univerjs/uniscript/lib/index.css';
  import '@univerjs/sheets-zen-editor/lib/index.css';

  import { IWorkbookData, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
  import { defaultTheme } from '@univerjs/design';
  import { zhCN } from 'univer:locales';

  import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
  import { DeviceInputEventType, UniverRenderEnginePlugin } from '@univerjs/engine-render';

  import { UniverUIPlugin } from '@univerjs/ui';

  import { UniverDocsPlugin } from '@univerjs/docs';
  import { UniverDocsUIPlugin } from '@univerjs/docs-ui';

  import { SetWorksheetActiveOperation, UniverSheetsPlugin, WorkbookEditablePermission } from '@univerjs/sheets';
  import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
  import { UniverSheetsFormulaUIPlugin } from '@univerjs/sheets-formula-ui';
  import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
  import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';
  // import { UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';
  // import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';
  import { UniverDrawingPlugin } from '@univerjs/drawing';
  import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui';
  import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing';
  import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';
  import { UniverFindReplacePlugin } from '@univerjs/find-replace';
  import { UniverSheetsFindReplacePlugin } from '@univerjs/sheets-find-replace';
  import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
  import { UniverSheetsSortPlugin } from '@univerjs/sheets-sort';
  import { UniverSheetsSortUIPlugin } from '@univerjs/sheets-sort-ui';
  import { UniverSheetsFilterUIPlugin } from '@univerjs/sheets-filter-ui';
  import { UniverDataValidationPlugin } from '@univerjs/data-validation';
  import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation';
  import { UniverSheetsDataValidationUIPlugin } from '@univerjs/sheets-data-validation-ui';
  import { UniverSheetsConditionalFormattingPlugin } from '@univerjs/sheets-conditional-formatting';
  import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-conditional-formatting-ui';
  import { UniverSheetsCrosshairHighlightPlugin } from '@univerjs/sheets-crosshair-highlight';
  import { UniverSheetsPivotTablePlugin } from '@univerjs-pro/sheets-pivot';
  import { UniverSheetsPivotTableUIPlugin } from '@univerjs-pro/sheets-pivot-ui';
  import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';
  import { UniverThreadCommentPlugin } from '@univerjs/thread-comment';
  import { UniverSheetsThreadCommentBasePlugin } from '@univerjs/sheets-thread-comment-base';
  import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';
  import { UniverUniscriptPlugin } from '@univerjs/uniscript';
  import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';
  // import { UniverWatermarkPlugin } from '@univerjs/watermark';

  import { JnpfFUniver } from './univer/facade';

  import { JnpfSheetsPlugin } from './univer/plugins/sheet.plugin';
  import { JnpfSheetsExcelFilePlugin } from './univer/plugins/sheet-excel-file.plugin';
  import { JnpfSheetsEchartPlugin } from './univer/plugins/sheet-echart.plugin';
  import { JnpfSheetsPreviewPlugin } from './univer/plugins/sheet-preview.plugin';
  import { JnpfSheetsPrintPlugin } from './univer/plugins/sheet-print.plugin';

  import { reactive, toRefs } from 'vue';
  import { buildUUID } from './univer/utils/uuid';
  import { useJnpfUniverStore } from './store';

  import {
    JnpfCommandIds,
    DefaultEchartOptions,
    JnpfUniverEchartKey,
    DefaultPrintConfig,
    JnpfPaperTypeOptions,
    JnpfPrintAreaOptions,
    JnpfPrintDirectionOptions,
    JnpfPrintHAlignOptions,
    JnpfPrintScaleOptions,
    JnpfPrintVAlignOptions,
  } from './univer/utils/define';
  import { correctSheetCellData, isEmptyObject, isNullOrUndefined, moveArrayValueToEnd } from './univer/utils';
  import { CreateUnitProps, DeliverCellDataProps, DeliverEchartOptionProps, State } from './index';

  defineOptions({ name: 'JnpfUniver' });
  const emits = defineEmits(['preview', 'focusEchart', 'changeCellFromSelection']);

  const state = reactive<State>({
    containerEleId: null,
    univer: null,
    jnpfUniverAPI: null,

    activeWorkbook: null,
    activeWorkbookId: null,
    activeWorksheet: null,
    activeWorksheetId: null,

    selectionChangeMonitor: null,
    beforeCommandExecuteMonitor: null,
    commandExecuteMonitor: null,

    isHiddenGridlines: true,

    loading: false,
  });
  const {
    containerEleId,
    univer,
    jnpfUniverAPI,
    activeWorkbook,
    activeWorkbookId,
    activeWorksheet,
    activeWorksheetId,
    selectionChangeMonitor,
    beforeCommandExecuteMonitor,
    commandExecuteMonitor,
    isHiddenGridlines,
    loading,
  } = toRefs(state);

  const dynamicJnpfUniverStoreId = `jnpfUniver_${buildUUID()}`;
  state.containerEleId = dynamicJnpfUniverStoreId;

  const jnpfUniverStore = useJnpfUniverStore(dynamicJnpfUniverStoreId);

  // 创建工作簿
  function handleCreateDesignUnit(options?: CreateUnitProps) {
    handleDisposeUnit(); // 销毁实例

    const {
      mode = 'design',
      snapshot: workbookData,
      echarts = {},
      uiHeader = true,
      uiFooter = true,
      uiContextMenu = true,
      readonly = false,
      defaultActiveSheetId,
      loading: createLoading = false,
    } = options ?? {};

    loading.value = createLoading;

    const containerEle = getDesignContainerEle();
    if (!containerEle) {
      console.warn('实例构建失败，无法找到设计器容器');
      return;
    }

    const realWorkbookData = !workbookData ? {} : analysisCreateUnitData(workbookData, mode, readonly);

    const univerInstance = createUniverInstance({
      container: containerEle,
      header: readonly ? false : uiHeader,
      footer: uiFooter,
      contextMenu: uiContextMenu,
      workbookData: realWorkbookData,
    });

    univer.value = univerInstance;
    jnpfUniverAPI.value = JnpfFUniver.newAPI(univerInstance);

    activeWorkbook.value = jnpfUniverAPI.value?.getActiveWorkbook();
    activeWorkbookId.value = activeWorkbook.value?.getId();
    // 改变默认激活的工作表
    if (defaultActiveSheetId) {
      jnpfUniverAPI.value?.executeCommand(SetWorksheetActiveOperation.id, { unitId: activeWorkbookId.value, subUnitId: defaultActiveSheetId });
    }
    activeWorksheet.value = activeWorkbook.value?.getActiveSheet();
    activeWorksheetId.value = activeWorksheet.value?.getSheetId();

    jnpfUniverStore?.updateModeCache(mode);
    jnpfUniverStore?.updateJnpfUniverApi(jnpfUniverAPI.value);
    jnpfUniverAPI.value?.getSheetsEchart()?.savePiniaStoreId(dynamicJnpfUniverStoreId);
    jnpfUniverStore?.updateEchartItems(echarts);

    setWorkbookPermission(mode, readonly);
    bindUniverLifeCycle(realWorkbookData);

    bindSelectionChange(mode, readonly);
    bindBeforeCommandExecute();
    bindAfterCommandExecuted();

    return {
      jnpfUniverAPI: jnpfUniverAPI.value,
    };
  }

  // 创建univer实例出来
  function createUniverInstance(config: any) {
    const { container, header, footer, contextMenu, workbookData } = config ?? {};

    const univerInstance = new Univer({
      theme: defaultTheme,
      locale: LocaleType.ZH_CN,
      locales: {
        [LocaleType.ZH_CN]: zhCN,
      },
      // logLevel: LogLevel.WARN,
    });

    univerInstance.registerPlugin(UniverRenderEnginePlugin);
    univerInstance.registerPlugin(UniverFormulaEnginePlugin);
    univerInstance.registerPlugin(UniverUIPlugin, {
      container,
      header,
      footer,
      contextMenu,
    });
    univerInstance.registerPlugin(UniverDocsPlugin);
    univerInstance.registerPlugin(UniverDocsUIPlugin);
    univerInstance.registerPlugin(UniverSheetsPlugin);
    univerInstance.registerPlugin(UniverSheetsUIPlugin);
    univerInstance.registerPlugin(UniverSheetsFormulaPlugin);
    univerInstance.registerPlugin(UniverSheetsFormulaUIPlugin);
    univerInstance.registerPlugin(UniverSheetsNumfmtPlugin);

    // 这个和注销的冲突掉了
    // univerInstance.registerPlugin(UniverSheetsHyperLinkPlugin);
    // univerInstance.registerPlugin(UniverSheetsHyperLinkUIPlugin);

    univerInstance.registerPlugin(UniverDrawingPlugin);
    univerInstance.registerPlugin(UniverDrawingUIPlugin);
    univerInstance.registerPlugin(UniverSheetsDrawingPlugin);
    univerInstance.registerPlugin(UniverSheetsDrawingUIPlugin);
    univerInstance.registerPlugin(UniverFindReplacePlugin);
    univerInstance.registerPlugin(UniverSheetsFindReplacePlugin);
    univerInstance.registerPlugin(UniverSheetsFilterPlugin);
    univerInstance.registerPlugin(UniverSheetsFilterUIPlugin);
    univerInstance.registerPlugin(UniverSheetsSortPlugin);
    univerInstance.registerPlugin(UniverSheetsSortUIPlugin);
    univerInstance.registerPlugin(UniverDataValidationPlugin);
    univerInstance.registerPlugin(UniverSheetsDataValidationPlugin);
    univerInstance.registerPlugin(UniverSheetsDataValidationUIPlugin, {
      showEditOnDropdown: true,
    });
    univerInstance.registerPlugin(UniverSheetsConditionalFormattingPlugin);
    univerInstance.registerPlugin(UniverSheetsConditionalFormattingUIPlugin);
    univerInstance.registerPlugin(UniverSheetsCrosshairHighlightPlugin);
    univerInstance.registerPlugin(UniverSheetsPivotTablePlugin);
    univerInstance.registerPlugin(UniverSheetsPivotTableUIPlugin);
    univerInstance.registerPlugin(UniverThreadCommentPlugin);
    univerInstance.registerPlugin(UniverThreadCommentUIPlugin);
    univerInstance.registerPlugin(UniverSheetsThreadCommentBasePlugin);
    univerInstance.registerPlugin(UniverSheetsThreadCommentPlugin);
    univerInstance.registerPlugin(UniverUniscriptPlugin);
    univerInstance.registerPlugin(UniverSheetsZenEditorPlugin);
    // univerInstance.registerPlugin(UniverWatermarkPlugin);

    univerInstance.registerPlugin(JnpfSheetsPlugin);
    univerInstance.registerPlugin(JnpfSheetsExcelFilePlugin);
    univerInstance.registerPlugin(JnpfSheetsEchartPlugin);
    univerInstance.registerPlugin(JnpfSheetsPreviewPlugin);
    univerInstance.registerPlugin(JnpfSheetsPrintPlugin);

    univerInstance.createUnit(UniverInstanceType.UNIVER_SHEET, workbookData);

    return univerInstance;
  }

  // 设置unit权限
  function setWorkbookPermission(mode: string, readonlyState: boolean) {
    if (mode === 'design' && !readonlyState) {
      return;
    }

    const permission = jnpfUniverAPI.value?.getPermission();
    permission.setWorkbookPermissionPoint(activeWorkbookId.value, WorkbookEditablePermission, false);
    permission.setPermissionDialogVisible(false);

    // activeWorksheet.value?.setHiddenGridlines(true);
    // activeWorksheet.value?.setHiddenGridlines(isHiddenGridlines.value);
  }

  // 绑定univer的生命周期
  function bindUniverLifeCycle(workbookData: IWorkbookData) {
    const univerHooks = jnpfUniverAPI.value?.getHooks();
    // 生命周期文档地址：https://univer.ai/zh-CN/guides/sheet/features/core/general-api
    univerHooks?.onStarting(() => {
      // emits('onStarting');
    });
    univerHooks?.onReady(() => {
      // emits('onReady');
    });
    univerHooks?.onRendered(() => {
      // jnpfUniverAPI.value?.registerSheetMainExtension(activeWorkbookId.value, new SheetMainExtension());
      // emits('onRendered');
    });
    univerHooks?.onSteady(() => {
      const { resources = [] } = workbookData ?? {};

      // 定义辅助函数检查目标组件类型
      const hasEchartComponent = (sheetData: Record<string, any>) =>
        Object.values(sheetData).some((floatDomValue: any) => floatDomValue?.componentKey === JnpfUniverEchartKey);

      // 使用 `some` 实现早停逻辑
      const activeWorksheetHasEchartState = resources.some((resource: any) => {
        if (resource?.name !== 'SHEET_DRAWING_PLUGIN') return false;

        const parsedResourceData = JSON.parse(resource?.data || '{}');
        const sheetValue = parsedResourceData?.[activeWorksheetId.value];

        return sheetValue?.data && hasEchartComponent(sheetValue.data);
      });

      // 根据结果更新状态
      if (activeWorksheetHasEchartState) {
        setTimeout(() => {
          loading.value = false;
        }, 500);
      } else {
        loading.value = false;
      }
    });
  }

  // 绑定选择变更事件
  function bindSelectionChange(mode: string, readonlyState: boolean) {
    if (mode === 'design' && !readonlyState) {
      selectionChangeMonitor.value = activeWorkbook.value?.onSelectionChange((params: any) => {
        if (!params?.length) {
          return;
        }

        const firstCell = params[0] ?? {}; // 业务逻辑只选取第一个
        const { startColumn, startRow } = firstCell;

        const cellData = jnpfUniverAPI.value?.getSheetsCell()?.getCellData(startColumn, startRow) ?? {};

        emits('changeCellFromSelection', {
          startRow,
          startColumn,
          cellData,
        });
      });
    }
  }

  // 绑定监听命令执行之前
  function bindBeforeCommandExecute() {
    beforeCommandExecuteMonitor.value = jnpfUniverAPI.value?.onBeforeCommandExecute((command: any) => {
      const { id: commandId } = command ?? {};

      if (commandId === 'sheet.operation.set-worksheet-active') {
        if (activeWorkbook.value) {
          // console.log('即将改变工作本');
        }
      }
    });
  }

  // 绑定监听命令执行之后
  function bindAfterCommandExecuted() {
    commandExecuteMonitor.value = jnpfUniverAPI.value?.onCommandExecuted((command: any) => {
      const { id: commandId } = command ?? {};

      if (commandId === 'sheet.operation.set-worksheet-active') {
        if (activeWorkbook.value) {
          activeWorksheet.value = activeWorkbook.value?.getActiveSheet();
          activeWorksheetId.value = activeWorksheet.value?.getSheetId();

          // if (workbookReadonly) {
          // activeWorksheet.value?.setHiddenGridlines(true); // 不显示网格
          // activeWorksheet.value?.setHiddenGridlines(true || isHiddenGridlines.value);
          // }
        }
      }

      if (commandId === 'sheet.mutation.toggle-gridlines') {
        const {
          params: { showGridlines },
        } = command;

        isHiddenGridlines.value = !Boolean(showGridlines);
      }

      if (commandId === JnpfCommandIds.insertedEchart) {
        // 插入图表
        const { drawingId } = command?.params ?? {};
        if (!drawingId) {
          return;
        }

        const echartItemsCache = jnpfUniverStore?.echartItemsCache;

        const updateItems = {
          ...echartItemsCache,
          [drawingId]: command?.params,
        };

        jnpfUniverStore?.updateEchartItems(updateItems);
      }

      if (commandId === JnpfCommandIds.focusEchart) {
        // 聚焦图表
        const { drawingId } = command?.params ?? {};
        if (!drawingId) {
          return;
        }

        const res = jnpfUniverStore?.getEchartItemByDrawingId(drawingId);
        if (!res) {
          return;
        }

        const { echartType, option } = res ?? {};

        emits('focusEchart', { drawingId, echartType, option } as DeliverEchartOptionProps);
      } else {
        jnpfUniverAPI.value?.getSheetsEchart()?.clearFocusDrawingId();
      }

      if (commandId === JnpfCommandIds.preview) {
        emits('preview');
      }
    });
  }

  // 解析创建数据
  function analysisCreateUnitData(workbookData: string | IWorkbookData, mode: string, readonlyState: boolean) {
    try {
      const parseWorkbookData = typeof workbookData === 'string' ? JSON.parse(workbookData) : workbookData;
      if (mode === 'design' && !readonlyState) {
        return parseWorkbookData;
      }

      const { resources = [] } = parseWorkbookData ?? {};
      const updatedResources = resources?.map((resource: any) => {
        if (resource?.name === 'SHEET_DRAWING_PLUGIN') {
          const parseResourceData = JSON.parse(resource?.data) ?? {};

          const updatedParseResourceData = Object.fromEntries(
            Object.entries(parseResourceData)?.map(([sheetKey, sheetValue]: any) => {
              const sheetData = sheetValue?.data || {};

              const updatedSheetData = Object.fromEntries(
                Object.entries(sheetData).map(([floatDomKey, floatDomValue]: any) => {
                  const { componentKey, ...sheetDataRest } = floatDomValue || {};

                  if (componentKey === JnpfUniverEchartKey) {
                    return [
                      floatDomKey,
                      {
                        ...sheetDataRest,
                        componentKey,
                        allowTransform: false,
                      },
                    ];
                  } else {
                    return [floatDomKey, floatDomValue];
                  }
                }),
              );

              return [sheetKey, { ...sheetValue, data: updatedSheetData }];
            }),
          );

          return {
            ...resource,
            data: JSON.stringify(updatedParseResourceData),
          };
        } else {
          return resource;
        }
      });

      return {
        ...parseWorkbookData,
        resources: updatedResources,
      };
    } catch (e) {
      console.error(e);
      return {};
    }
  }

  // 暴露 - 获取设计的工作表数据
  function getDesignWorkbookData() {
    const echartItemsCache = jnpfUniverStore?.echartItemsCache;
    const snapshot = activeWorkbook.value ? activeWorkbook.value?.save() : null;

    const updateEcharts: Record<string, any> = {};

    // 给图表增加dom的id并且剔除已被删除的图表数据
    const { resources = [], sheets = {} } = snapshot ?? {};
    const updatedResources = resources?.map((resource: any) => {
      if (resource?.name === 'SHEET_DRAWING_PLUGIN') {
        const parseResourceData = JSON.parse(resource?.data) ?? {};

        const updatedParseResourceData = Object.fromEntries(
          Object.entries(parseResourceData)?.map(([sheetKey, sheetValue]: any) => {
            const sheetData = sheetValue?.data || {};

            const updatedSheetData = Object.fromEntries(
              Object.entries(sheetData).map(([floatDomKey, floatDomValue]: any) => {
                const { componentKey, drawingId, props = {}, ...sheetDataRest } = floatDomValue || {};

                if (componentKey === JnpfUniverEchartKey) {
                  if (echartItemsCache?.hasOwnProperty(drawingId)) {
                    updateEcharts[drawingId] = { ...echartItemsCache[drawingId] };
                  }

                  const domId = echartItemsCache?.[drawingId]?.domId;
                  const updatedProps = {
                    ...props,
                    id: domId,
                  };

                  return [
                    floatDomKey,
                    {
                      ...sheetDataRest,
                      drawingId,
                      componentKey,
                      props: updatedProps,
                    },
                  ];
                } else {
                  return [floatDomKey, floatDomValue];
                }
              }),
            );

            return [sheetKey, { ...sheetValue, data: updatedSheetData }];
          }),
        );

        return {
          ...resource,
          data: JSON.stringify(updatedParseResourceData),
        };
      } else {
        return resource;
      }
    });

    // 取出所有自定义的custom
    const customs: any[] = [];
    for (const sheetKey in sheets) {
      const sheet = sheets[sheetKey];
      const sheetCellData = sheet?.cellData;

      if (!sheetCellData) continue;
      for (const rowKey in sheetCellData) {
        const row = sheetCellData[rowKey];

        for (const colKey in row) {
          const cellData = row[colKey];
          const custom = cellData?.custom;

          if (custom && !isEmptyObject(custom)) {
            customs.push({
              sheetId: sheetKey,
              row: rowKey,
              col: colKey,
              cellData,
            });
          }
        }
      }
    }

    return {
      snapshot: {
        ...snapshot,
        resources: updatedResources,
      },
      echarts: updateEcharts,
      customs,
    };
  }

  // 暴露 - 获取预览的工作表数据
  function getPreviewWorkbookData() {
    const designData = getDesignWorkbookData();
    const { snapshot, echarts, customs } = designData ?? {};

    const { resources = [], sheets } = snapshot ?? {};
    const updateSheets = { ...sheets };

    const updatedResources = resources?.map((resource: any) => {
      if (resource?.name === 'SHEET_DRAWING_PLUGIN') {
        const parseResourceData = JSON.parse(resource?.data ?? '{}');

        const updatedParseResourceData = Object.fromEntries(
          Object.entries(parseResourceData)?.map(([sheetKey, sheetResource]: any) => {
            const { data: sheetData = {}, order: originalOrder = [] } = sheetResource || {};

            // 存在浮动元素，如果没有单元格数据会出现浮动元素丢失，特处理此bug
            if (originalOrder.length) {
              const { cellData, rowCount, columnCount } = sheets[sheetKey] ?? {};
              const updateCellData = correctSheetCellData(cellData, rowCount, columnCount);

              updateSheets[sheetKey] = {
                ...sheets[sheetKey],
                cellData: updateCellData,
              };
            }

            let sheetOrder = [...originalOrder]; // 使用一个可变的引用来追踪顺序更新

            const updatedSheetData = Object.fromEntries(
              Object.entries(sheetData).map(([floatDomKey, floatDomValue]: any) => {
                const { unitId, subUnitId, drawingId, componentKey, sheetTransform, transform, props } = floatDomValue || {};

                if (componentKey === JnpfUniverEchartKey) {
                  const { id: domId } = props ?? {};

                  sheetOrder = moveArrayValueToEnd(sheetOrder, drawingId);

                  return [
                    floatDomKey,
                    {
                      drawingId,
                      drawingType: 0,
                      imageSourceType: 'BASE64',
                      sheetTransform,
                      source: jnpfUniverStore?.echartImgItemsCache?.[domId],
                      subUnitId,
                      transform,
                      unitId,
                    },
                  ];
                } else {
                  return [floatDomKey, floatDomValue];
                }
              }),
            );

            return [sheetKey, { ...sheetResource, data: updatedSheetData, order: sheetOrder }];
          }),
        );

        return {
          ...resource,
          data: JSON.stringify(updatedParseResourceData),
        };
      } else {
        return resource;
      }
    });

    return {
      snapshot: {
        ...snapshot,
        sheets: updateSheets,
        resources: updatedResources,
      },
      echarts,
      customs,
    };
  }

  // 更新图表配置
  function updateEchartOption(deliverConfig: DeliverEchartOptionProps) {
    const { drawingId, echartType, option } = deliverConfig;

    // 校验参数
    if (!drawingId || !jnpfUniverAPI.value) return;

    const echartItemsCache = jnpfUniverStore?.echartItemsCache;
    const currentParams = echartItemsCache?.[drawingId];

    if (!currentParams) return;

    const updatedParams = {
      ...currentParams,
      echartType,
      option,
    };

    const updatedItemsCache = {
      ...echartItemsCache,
      [drawingId]: updatedParams,
    };

    jnpfUniverStore?.updateEchartItems(updatedItemsCache);

    const { domId } = currentParams;
    jnpfUniverStore?.updateFocusEchartItem({
      domId,
      drawingId,
      option,
    });
  }

  // 暴露 - 更新多个单元格值
  function updateCellsData(updateCellsData: DeliverCellDataProps[]) {
    if (!updateCellsData?.length) {
      return;
    }

    updateCellsData?.forEach((config: any) => {
      const { startColumn, startRow, cellData: configuringCellData = {} } = config ?? {};

      if (isNullOrUndefined(startColumn) || isNullOrUndefined(startRow)) {
        return;
      }

      const oldCellData = jnpfUniverAPI.value?.getSheetsCell()?.getCellData(startColumn, startRow) ?? {};

      const { v = '', custom = {} } = configuringCellData;
      const { type } = custom;

      // 纯文本
      if (!type || type === 'text') {
        const newCellData = {
          ...oldCellData,
          v,
          custom: {
            ...(oldCellData?.custom ?? {}),
            ...custom,
            type,
          },
        };

        delete newCellData?.t;
        delete newCellData?.custom?.type;

        if (isEmptyObject(newCellData?.custom)) {
          delete newCellData?.custom;
        }

        handleSetCellData({ newCellData, startColumn, startRow });
      }

      // 数据集
      if (type === 'dataSource') {
        const newCellData = {
          ...oldCellData,
          v: isNullOrUndefined(v) || v === '' ? '' : `\${${v}}`,
          t: 1,
          custom: {
            ...(oldCellData?.custom ?? {}),
            ...custom,
            type,
          },
        };

        handleSetCellData({ newCellData, startColumn, startRow });
      }
    });
  }

  // 设置单元格值
  function handleSetCellData(config: any) {
    const { newCellData, startColumn, startRow } = config ?? {};

    const updateResult = jnpfUniverAPI.value?.getSheetsCell()?.setCellData(startColumn, startRow, newCellData);
    if (!updateResult) {
      return;
    }

    jnpfUniverAPI.value?.getSheetsCell()?.refreshRangeCellsView(activeWorksheet.value?.getRange(startRow, startColumn));
  }

  // 获取设计器容器元素
  function getDesignContainerEle() {
    if (!containerEleId.value) {
      return false;
    }

    const containerEle = document.getElementById(containerEleId.value);
    return containerEle || false;
  }

  // 销毁工作簿
  function handleDisposeUnit() {
    if (activeWorkbookId?.value) {
      loading.value = true;

      selectionChangeMonitor.value && selectionChangeMonitor.value?.dispose();
      beforeCommandExecuteMonitor.value && beforeCommandExecuteMonitor.value?.dispose();
      commandExecuteMonitor.value && commandExecuteMonitor.value?.dispose();

      jnpfUniverAPI.value && jnpfUniverAPI.value?.disposeUnit(activeWorkbookId.value);

      resetUniverState();

      jnpfUniverStore?.resetStore();

      loading.value = false;
    } else {
      // console.warn('销毁工作簿失败');
    }
  }

  // 重置实例状态
  function resetUniverState() {
    univer.value = null;
    jnpfUniverAPI.value = null;

    activeWorkbook.value = null;
    activeWorkbookId.value = null;
    activeWorksheet.value = null;
    activeWorksheetId.value = null;

    selectionChangeMonitor.value = null;
    beforeCommandExecuteMonitor.value = null;
    commandExecuteMonitor.value = null;

    isHiddenGridlines.value = true;

    loading.value = false;
  }

  // 渲染单元格图标
  function handleRenderCellIcon() {
    console.log(333);
  }

  // 暴露 - 让单元格失焦
  async function setCellEditVisible(): Promise<void> {
    if (!jnpfUniverAPI.value) {
      return;
    }

    jnpfUniverAPI.value?.executeCommand('sheet.operation.set-cell-edit-visible', {
      visible: false,
      _eventType: DeviceInputEventType.PointerUp,
    });

    return new Promise(resolve => {
      setTimeout(() => {
        resolve();
      }, 200);
    });
  }

  // 暴露 - 获取工作簿id
  function getActiveWorkbookId() {
    return activeWorkbookId.value ?? null;
  }

  // 暴露 - 获取激活的工作本id
  function getActiveWorksheetId() {
    return activeWorksheetId.value ?? null;
  }

  // 暴露 - 获取默认的图表配置
  function getDefaultEchartOptions() {
    return { ...DefaultEchartOptions };
  }

  // 暴露 - 获取默认的打印配置
  function getPrintConfigs() {
    return {
      printAreaOptions: JnpfPrintAreaOptions,
      paperTypeOptions: JnpfPaperTypeOptions,
      printDirectionOptions: JnpfPrintDirectionOptions,
      printScaleOptions: JnpfPrintScaleOptions,
      printVAlignOptions: JnpfPrintVAlignOptions,
      printHAlignOptions: JnpfPrintHAlignOptions,
      defaultConfigForm: DefaultPrintConfig,
    };
  }

  defineExpose({
    handleCreateDesignUnit,
    getDesignWorkbookData,
    getPreviewWorkbookData,
    handleDisposeUnit,
    updateEchartOption,
    updateCellsData,
    handleRenderCellIcon,
    getActiveWorkbookId,
    getActiveWorksheetId,
    setCellEditVisible,
    getDefaultEchartOptions,
    getPrintConfigs,
  });
</script>

<style lang="less" scoped>
  .jnpf-univer-design-content {
    flex: 1;
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;
    position: relative;

    .univer-design-container {
      width: 100%;
      height: calc(100%);
    }
  }
</style>
